import hashlib
import re
import time
from flask import json
from schema.Mark import *


def get_md5(item):
    res = json.dumps(item)
    m = hashlib.md5(res.encode(encoding='gb2312'))
    return m.hexdigest()


def clean_mark(item, msg):
    uid = get_md5(item)
    if 'rate' in item:
        item['rate'] = item['rate'].replace('%', "")

    if 'amount' in item:
        item['amount'] = h_amount(item['amount'])

    if 'start_time' in item:
        tunk = item['start_time']
        try:
            tunk = tunk.split('】')[1]
        except:
            pass

        tunk = tunk.replace("-", "")

        if msg == 'sichouzhilu':
            tunk = tunk[:4] + "-" + tunk[4:6] + "-00"
            print(msg, ":", tunk)
        if msg == 'muniuniuma':
            a = int(tunk.strip()) / 1000
            timeArray = time.localtime(a)
            otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
            tunk = otherStyleTime

        item['start_time'] = tunk

    mark = Mark(**item)
    mark.id = uid
    return mark


def h_amount(amount):
    amount = str(amount).strip()
    unit = 1
    if re.search('万元', amount):
        amount = amount.replace('万元', "")
        unit = 10000

    if re.search('百万', amount):
        amount = amount.replace('百万', "")
        unit = 10000 * 100
    amount = float(amount)
    return amount * unit
